package ahblue.cn.tanzi.ui.home.article;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.adapter.BRAdapter;
import ahblue.cn.tanzi.adapter.RvHolder;
import ahblue.cn.tanzi.data.Result;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.jmessage.im.util.ToastUtil;
import ahblue.cn.tanzi.model.home.ArticleDetail;
import ahblue.cn.tanzi.model.home.VideoCommentlModel;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.ui.base.BaseActivity;
import ahblue.cn.tanzi.util.ImageLoadUtil;
import ahblue.cn.tanzi.util.TimeUtils;
import ahblue.cn.tanzi.util.VipUtils;
import ahblue.cn.tanzi.view.MyWebView;
import ahblue.cn.tanzi.view.decoration.SimpleItemDecoration;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 显示文章内容
 */
public class ArticleDetailActivity extends BaseActivity {

    public final static String ARG_ARTICLE_ID = "ARG_ARTICLE_ID";
    public final static String ARG_ARTICLE_TITLE = "ARG_ARTICLE_TITLE";
    private int page = 0;
    private String pageCount = "200";
    private boolean isFirst = true;


    @BindView(R.id.webViewArticle)
    MyWebView mWebViewArticle;
    @BindView(R.id.iv_collect)
    TextView mTextViewCollect;
    @BindView(R.id.tv_like)
    TextView mTextViewLike;
    @BindView(R.id.tv_like_title)
    TextView mTextViewLikeTitle;
    @BindView(R.id.tv_comment_title)
    TextView mTextCommentTitle;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.textViewTitle)
    TextView textViewTitle;
    private List<VideoCommentlModel.CommentBean> dataList = new ArrayList<>();
    private BRAdapter<VideoCommentlModel.CommentBean> adapter;
    private LoginResultModel mLoginResultModel;
    private int mArticleId;
    private ArticleDetail mArticleDetail;
    private String mArticTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_detail);
        ButterKnife.bind(this);
        if (!VipUtils.checkVip(this)) {
            finish();
            return;
        }

        final Intent intent = getIntent();
        mArticleId = intent.getIntExtra(ARG_ARTICLE_ID, 0);
        mArticTitle = intent.getStringExtra(ARG_ARTICLE_TITLE);
        if (!TextUtils.isEmpty(mArticTitle)){
            textViewTitle.setText(mArticTitle);
        }
        if (mArticleId == 0) {
            finish();
            return;
        }
        initRecy();
        initData();
        initView();

    }

    private void initRecy() {
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.addItemDecoration(new SimpleItemDecoration(this));
        adapter = new BRAdapter<VideoCommentlModel.CommentBean>(this, R.layout.activity_comment_item, dataList) {
            @Override
            protected void convert(RvHolder holder, VideoCommentlModel.CommentBean specalModel, int position) {
                holder.setText(R.id.name, TextUtils.isEmpty(specalModel.user_data.member_name) ? specalModel.user_data.member_id : specalModel.user_data.member_name);
                holder.setText(R.id.content, specalModel.comment_content);
                ImageLoadUtil.load(ArticleDetailActivity.this, specalModel.user_data.member_avatar, holder.getView(R.id.img));
                holder.setText(R.id.time, TimeUtils.getStandardDate(specalModel.add_time));
//                holder.setText(R.id.count, "点赞 "+specalModel.fabulous_count + "");
            }
        };
        recycler.setAdapter(adapter);
    }

    private void initComment() {
        VideoCommentlModel.getArticComment(this, mArticleDetail.article.id+"", page, pageCount, new VideoCommentlModel.VideoCommentResult() {
            @Override
            public void conver(VideoCommentlModel model) {
                dataList.clear();
                dataList.addAll(model.comment);
                if (dataList.size() == 0) {
//                    rlempty.setVisibility(View.VISIBLE);
                    recycler.setVisibility(View.GONE);
                } else {
//                    rlempty.setVisibility(View.GONE);
                    recycler.setVisibility(View.VISIBLE);
                }
                mTextCommentTitle.setText("评论（" + model.count + "）");
                adapter.notifyDataSetChanged();
            }
        });
    }


    private void initData() {
        mLoginResultModel = LoginResultModel.getUserModel(this, LoginResultModel.class);

        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotArticleDetail(mArticleId, mLoginResultModel.token, mCallbackArticleDetail);
    }

    private void initView() {
        WebSettings settings = mWebViewArticle.getSettings();
        settings.setJavaScriptEnabled(true);
        mWebViewArticle.getSettings().setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }

    @OnClick(R.id.imageButtonLeft)
    void onClickImageButtonLeft() {
        finish();
    }

    // 写评论
    @OnClick(R.id.tv_write_comment)
    void onClickWriteComment() {
        final Intent intent = new Intent(this, AddCommentActivity.class);
        intent.putExtra(AddCommentActivity.ARG_ARTICAL_ID, mArticleId);
        intent.putExtra(AddCommentActivity.ARG_COMMENT_TYPE, 1);
        startActivityForResult(intent,500);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*if (resultCode != Activity.RESULT_OK) {
            return;
        }*/
        if (requestCode==500){
            initComment();
        }
    }

    // 收藏
    @OnClick(R.id.iv_collect)
    void onClickCollect() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotArticleCollection(mArticleId, "collection", mLoginResultModel.token,
                new ApiCallback<Result>() {

                    @Override
                    public void onSuccess(Result data) {
                        Drawable topDrawable = getResources().getDrawable(R.drawable.icon_mark_fill);
                        topDrawable.setBounds(0, 0, topDrawable.getMinimumWidth(), topDrawable.getMinimumHeight());

                        mTextViewCollect.setCompoundDrawables(null, topDrawable, null, null);
                        mArticleDetail.article.collection_count++;
                        mTextViewCollect.setText("收藏（" + mArticleDetail.article.collection_count + "）");
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                    }
                });
    }

    // 点赞事件处理
    @OnClick(R.id.tv_like)
    void onClickLick() {
        if (mArticleDetail == null || mArticleDetail.article == null) {
            ToastUtil.shortToast(this, "操作失败");
            return;
        }
        if (mArticleDetail.article.is_fabulous == 0) {
            addLike();
        } else {
            removeLike();
        }
    }

    private void addLike() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotArticleCollection(mArticleId, "fabulous", mLoginResultModel.token,
                new ApiCallback<Result>() {

                    @Override
                    public void onSuccess(Result data) {
                        if (mArticleDetail == null || mArticleDetail.article == null) {
                            return;
                        }
                        mArticleDetail.article.is_fabulous = 1;
                        setLike(true);
                        mArticleDetail.article.fabulous_count++;
                        mTextViewLike.setText("点赞（" + mArticleDetail.article.fabulous_count + "）");
                        mTextViewLikeTitle.setText("点赞（" + mArticleDetail.article.fabulous_count + "）");
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        ToastUtil.shortToast(ArticleDetailActivity.this, "操作失败");
                    }
                });
    }

    private void removeLike() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.delBigShotArticleDeleteFabulous(mArticleId, mLoginResultModel.token,
                new ApiCallback<Result>() {

                    @Override
                    public void onSuccess(Result data) {
                        if (mArticleDetail == null || mArticleDetail.article == null) {
                            return;
                        }
                        mArticleDetail.article.is_fabulous = 0;
                        setLike(false);
                        mArticleDetail.article.fabulous_count--;
                        mTextViewLike.setText("点赞（" + mArticleDetail.article.fabulous_count + "）");
                        mTextViewLikeTitle.setText("点赞（" + mArticleDetail.article.fabulous_count + "）");
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        ToastUtil.shortToast(ArticleDetailActivity.this, "操作失败");
                    }
                });
    }

    private void updateArticleDetail(ArticleDetail articleDetail) {
        mWebViewArticle.setWebChromeClient(new WebChromeClient()
                {
                    public void onProgressChanged(WebView view, int progress)
                    {
                        //当进度走到100的时候做自己的操作，我这边是弹出dialog
                        if(progress == 100){
                            if (isFirst){
                                isFirst = false;
                                initComment();
                            }
                        }
                    }
                });
        mWebViewArticle.loadUrl(articleDetail.article.content_url);
        setCollect(articleDetail.article.is_collection == 1);
        setLike(articleDetail.article.is_fabulous == 1);

        mTextViewCollect.setText("收藏（" + mArticleDetail.article.collection_count + "）");
        mTextViewLike.setText("点赞（" + articleDetail.article.fabulous_count + "）");
        mTextViewLikeTitle.setText("点赞（" + articleDetail.article.fabulous_count + "）");
    }

    /**
     * 设置收藏的状态
     * @param state 状态
     */
    private void setCollect(boolean state) {
        int id = state ? R.drawable.icon_mark_fill : R.drawable.icon_mark_default;
        Drawable topDrawable = getResources().getDrawable(id);
        topDrawable.setBounds(0, 0, topDrawable.getMinimumWidth(), topDrawable.getMinimumHeight());

        mTextViewCollect.setCompoundDrawables(null, topDrawable, null, null);
    }

    /**
     * 设置点赞的状态
     * @param state 状态
     */
    private void setLike(boolean state) {
        int id = state ? R.drawable.icon_news_comment_fill : R.drawable.icon_news_comment;
        Drawable topDrawable = getResources().getDrawable(id);
        topDrawable.setBounds(0, 0, topDrawable.getMinimumWidth(), topDrawable.getMinimumHeight());

        mTextViewLike.setCompoundDrawables(null, topDrawable, null, null);
    }

    private ApiCallback<ArticleDetail> mCallbackArticleDetail = new ApiCallback<ArticleDetail>() {
        @Override
        public void onSuccess(ArticleDetail data) {
            mArticleDetail = data;
            updateArticleDetail(data);

        }

        @Override
        public void onFailed(String errorMsg) {
            if (errorMsg == null || errorMsg.length() == 0) {
                errorMsg = "未知错误";
            }

            Toast.makeText(ArticleDetailActivity.this, errorMsg, Toast.LENGTH_LONG).show();
            ArticleDetailActivity.this.finish();
        }
    };
}
